//
//  CMNetworkConnector.m
//  CocoaMesh
//
//  Created by George  Armah on 4/28/09.
//  Copyright 2009 Lafayette College. All rights reserved.
//

#import "CMNetworkConnector.h"
#import "CMCocoaMeshConstants.h"


@implementation CMNetworkConnector

+(NSData*)sendSynchronousRequest:(NSURLRequest *)request 
			   returningResponse:(NSURLResponse**)response 
						   error:(NSError**)err
{
	NSData * responseData = [NSURLConnection sendSynchronousRequest:request 
												  returningResponse:response 
															  error:err];
	
	//Handle HTTP Errors
	//Assuming that anything apart from 200 is bad, need to research this some more
	NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) *response;
	if ( httpResponse != nil && !([httpResponse statusCode] >= HTTP_STATUS_OK && [httpResponse statusCode] < HTTP_STATUS_REDIRECT ) )
	{
		NSString * statusCodeInfo = [NSString stringWithFormat:@"HTTP Status Code %i returned", [httpResponse statusCode]];
		NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
									NSLocalizedString(statusCodeInfo, @""), NSLocalizedDescriptionKey,
									httpResponse, HTTP_RESPONSE_KEY,
									nil];
		
		if ( *err != nil )
		{
			for (NSString * extraErrorInfo in errorDict)
			{
				[[*err userInfo] setValue:[errorDict valueForKey:extraErrorInfo] forKey:extraErrorInfo];
			}
		}
		else 
		{
			
			*err = [NSError errorWithDomain:CocoaMeshErrorDomain code:[httpResponse statusCode] userInfo:errorDict];
		}
	}
	
	return responseData;
}

@end
